package com.wms.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.common.QueryPageParam;
import com.wms.common.Result;
import com.wms.entity.Menu;
import com.wms.entity.User;
import com.wms.service.MenuService;
import com.wms.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;



/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wms
 * @since 2024-07-16
 */
@CrossOrigin
@RestController
@RequestMapping({"/user", "/api/user"})
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }

    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String no){
        List list= userService.lambdaQuery().eq(User::getNo,no).list();
        return list.size()>0?Result.suc(list):Result.fail();
    }

    //新增
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        return userService.save(user)?Result.suc():Result.fail();
    }

    //修改
    @PutMapping("/mod")
    public boolean mod(@RequestBody User user){
        return userService.updateById(user);
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        return userService.updateById(user) ? Result.suc() : Result.fail();
    }

    //删除
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return userService.removeById(id) ? Result.suc() : Result.fail();
    }

    //修改或新增
    @PutMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }

    //登录（不携带JWT）
    /*@PostMapping("/login")
    public Result login(@RequestBody User user) {
        List list=userService.lambdaQuery()
                .eq(User::getNo,user.getNo())
                .eq(User::getPassword,user.getPassword())
                .list();//查询用户是否存在

        if (list.size()>0){
            User user1= (User) list.get(0);//获取用户信息
            List menuList= menuService.lambdaQuery().like(Menu::getMenuright,user1.getRoleId()).list();//根据角色id查询菜单
            HashMap res=new HashMap();//返回用户信息及菜单
            res.put("user",user1);
            res.put("menu",menuList);
            //System.out.println("res=="+res);//打印用户信息及菜单
            return Result.suc(res);//返回用户信息及菜单
        }

        return Result.fail();
    }*/

    //删除
    @DeleteMapping("/delete")
    public boolean delete(Integer id){
        return userService.removeById(id);
    }

    //查询（模糊、匹配）
    @PostMapping("/listP")
    public Result listP(@RequestBody User user){
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(user.getName())){
            lambdaQueryWrapper.like(User::getName,user.getName());
        }
        return Result.suc(userService.list(lambdaQueryWrapper));
    }

    //分页查询
    @GetMapping("/listPage")
    public List<User> listPage(@RequestBody QueryPageParam queryPageParam){
        //System.out.println(queryPageParam);
        //System.out.println("num=="+queryPageParam.getPageNum());//当前页数
        //System.out.println("size=="+queryPageParam.getPageSize());//每页多少条数据

        HashMap param=queryPageParam.getParam();
        String name=(String)param.get("name");
        System.out.println("name=="+param.get("name"));
        //System.out.println("no=="+param.get("no"));

        Page<User> page=new Page<>(queryPageParam.getPageNum(), queryPageParam.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.page(page, lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @GetMapping("/listPageC")
    public List<User> listPageC(@RequestBody QueryPageParam queryPageParam){
        HashMap param=queryPageParam.getParam();
        String name=(String)param.get("name");
        System.out.println("name=="+param.get("name"));

        Page<User> page=new Page<>(queryPageParam.getPageNum(), queryPageParam.getPageSize());

        IPage result = userService.pageC(page);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @GetMapping("/listPageCC")
    public List<User> listPageCC(@RequestBody QueryPageParam queryPageParam){
        HashMap param=queryPageParam.getParam();
        String name=(String)param.get("name");
        System.out.println("name=="+param.get("name"));

        Page<User> page=new Page<>(queryPageParam.getPageNum(), queryPageParam.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam queryPageParam){
        HashMap param=queryPageParam.getParam();
        String name=(String)param.get("name");
        String sex=(String)param.get("sex");
        String roleId=(String)param.get("roleId");

        Page<User> page=new Page<>(queryPageParam.getPageNum(), queryPageParam.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(name) &&!"null".equals(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        if (StringUtils.isNotBlank(sex) ){
            lambdaQueryWrapper.like(User::getSex,sex);
        }
        if (StringUtils.isNotBlank(roleId) ){
            lambdaQueryWrapper.like(User::getRoleId,roleId);
        }
        //lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());
        //System.out.println(result.getRecords());
        return Result.suc(result.getRecords(), result.getTotal());//返回数据和总条数
    }

    /**
     * 获取当前用户信息及菜单列表
     *
     * @param request HttpServletRequest对象，用于获取JWT中的用户信息
     * @return Result对象，包含用户信息和菜单列表
     */
    @GetMapping({"/me", "/api/user/me"})
    public Result me(HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("jwtClaims");
        if (claims == null) {
            return Result.fail();
        }
        Long id = ((Number) claims.get("id")).longValue();
        User user = userService.getById(id);
        if (user == null) {
            return Result.fail();
        }
        List menuList = menuService.lambdaQuery().like(Menu::getMenuright, user.getRoleId()).list();
        HashMap res = new HashMap();
        res.put("user", user);
        res.put("menu", menuList);
        return Result.suc(res);
    }
}
